<template>
  <div class="event-detail-view">
    <h1>活动详情</h1>
    <el-card v-if="event" class="detail-card" shadow="always">
      <div class="detail-header">
        <img :src="posterUrl" alt="poster" class="poster" />
        <div class="info">
          <h2>{{ event.title }}</h2>
          <p>场馆：{{ event.venue }}</p>
          <p>地址：{{ event.address }}</p>
          <p>分类：{{ event.category || '未分类' }}</p>
          <p>开始时间：{{ formatDate(event.startTime) }}</p>
          <p>状态：{{ statusText(event.status) }}</p>
          <p>总座位：{{ event.totalSeats }}；可用座位：{{ event.availableSeats }}</p>
          <p>最低票价：¥{{ event.lowestPrice ?? '-' }}</p>
          <div class="poster-actions">
            <el-button type="primary" size="small" :loading="posterUploading" @click="choosePoster">更换海报</el-button>
            <input ref="posterInputRef" type="file" accept="image/*" class="hidden-input" @change="onPosterFileChange" />
          </div>
        </div>
      </div>
      <div class="desc" v-if="event.description">
        <h3>简介</h3>
        <p class="pre">{{ event.description }}</p>
      </div>
      <div class="actions">
        <el-button @click="goBack">返回列表</el-button>
        <el-button type="primary" @click="toggleEdit" v-if="!isEditing">编辑该活动</el-button>
        <el-button type="warning" @click="cancelEdit" v-else>取消编辑</el-button>
      </div>

      <el-divider />

      <div v-if="isEditing" class="edit-form">
        <h3>编辑活动信息</h3>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入活动标题" />
          </el-form-item>
          <el-form-item label="场馆" prop="venue">
            <el-input v-model="form.venue" placeholder="请输入场馆" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="分类" prop="category">
            <el-input v-model="form.category" placeholder="如：演唱会/戏剧" />
          </el-form-item>
          <el-form-item label="海报">
            <div class="poster-upload">
              <img :src="posterUrl" alt="poster" class="poster-sm" />
              <el-button type="primary" size="small" :loading="posterUploading" @click="choosePoster">上传海报</el-button>
            </div>
            <p class="hint">支持 png/jpg/jpeg/webp；最大 20MB；建议 1:1.5 尺寸。</p>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择开始时间"
              value-format="YYYY-MM-DDTHH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" class="w-160">
              <el-option :value="1" label="草稿" />
              <el-option :value="2" label="上架" />
              <el-option :value="3" label="下架" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveEdit" :loading="saving">保存</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-divider />

      <div class="tickets-edit">
        <h3>票务批量编辑</h3>
        <div class="tickets-toolbar">
          <el-button type="success" @click="addTicketRow">新增票务行</el-button>
          <el-button type="primary" :loading="savingTickets" @click="saveTicketsBatch">保存票务变更</el-button>
          <el-button @click="loadTickets" :loading="loadingTickets">刷新票务</el-button>
        </div>
        <el-table :data="tickets" border stripe v-loading="loadingTickets" style="width: 100%">
          <el-table-column prop="id" label="ID" width="90" />
          <el-table-column prop="ticketType" label="票种" min-width="160">
            <template #default="{ row }">
              <el-input v-model="row.ticketType" placeholder="如：VIP/看台A" />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="140">
            <template #default="{ row }">
              <el-input v-model.number="row.price" placeholder="数字" />
            </template>
          </el-table-column>
          <el-table-column prop="seatArea" label="区域" width="140">
            <template #default="{ row }"><el-input v-model="row.seatArea" /></template>
          </el-table-column>
          <el-table-column prop="seatRow" label="排" width="120">
            <template #default="{ row }"><el-input v-model="row.seatRow" /></template>
          </el-table-column>
          <el-table-column prop="seatNumber" label="座位" width="120">
            <template #default="{ row }"><el-input v-model="row.seatNumber" /></template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="160">
            <template #default="{ row }">
              <el-select v-model="row.status" class="w-140">
                <el-option :value="1" label="在售(1)" />
                <el-option :value="0" label="不可售(0)" />
                <el-option :value="2" label="已售(2)" />
                <el-option :value="3" label="锁定(3)" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="{ row, $index }">
              <el-button size="small" type="danger" @click="removeTicketRow(row, $index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <p class="hint">提示：点击“删除”仅在本地标记删除；保存后批量提交。新增行的 <code>ID</code> 将由后端创建。</p>
      </div>
    </el-card>
    <el-empty v-else description="未找到该活动" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { eventAPI } from '@/api'
import { BASE_URL } from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const event = ref(null)
const posterUrl = ref('')
const isEditing = ref(false)
const saving = ref(false)
const formRef = ref()
const form = ref({ title: '', venue: '', address: '', category: '', startTime: '', status: 1 })
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  venue: [{ required: true, message: '请输入场馆', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
}

function formatDate(dt) {
  if (!dt) return '-'
  const d = new Date(dt)
  return d.toLocaleString('zh-CN')
}
function statusText(s) { return s === 1 ? '草稿' : s === 2 ? '上架' : s === 3 ? '下架' : '未知' }

async function load() {
  const id = route.params.id
  try {
    const data = await eventAPI.getEventDetail(id)
    event.value = data
    posterUrl.value = data?.posterUrl ? `${BASE_URL}${data.posterUrl}` : `${BASE_URL}/images/phantom-opera.svg`
    // 同步到编辑表单
    form.value = {
      title: data?.title || '',
      venue: data?.venue || '',
      address: data?.address || '',
      category: data?.category || '',
      startTime: data?.startTime || '',
      status: data?.status ?? 1,
    }
    // 加载票务
    await loadTickets()
  } catch (err) {
    ElMessage.error(`加载活动详情失败：${err?.message || '请求错误'}`)
  }
}

function goBack() { router.push('/events') }
function toggleEdit() { isEditing.value = true }
function cancelEdit() { isEditing.value = false; if (event.value) { form.value = { ...form.value, ...{ title: event.value.title, venue: event.value.venue, address: event.value.address, category: event.value.category, startTime: event.value.startTime, status: event.value.status } } } }

async function saveEdit() {
  try {
    await formRef.value?.validate()
    saving.value = true
    const id = route.params.id
    const payload = { ...form.value }
    await ElMessageBox.confirm('确认保存当前修改？', '提示', { type: 'warning' })
    await eventAPI.updateEvent(id, payload)
    ElMessage.success('活动信息已更新')
    isEditing.value = false
    await load()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error(`保存失败：${err?.message || '请求错误'}`)
    }
  } finally {
    saving.value = false
  }
}

// 海报上传
const posterUploading = ref(false)
const posterInputRef = ref(null)
function choosePoster() {
  posterInputRef.value && posterInputRef.value.click()
}
async function onPosterFileChange(e) {
  const f = e.target.files?.[0]
  if (!f) return
  const id = route.params.id
  const fd = new FormData()
  fd.append('file', f)
  try {
    posterUploading.value = true
    const resp = await eventAPI.uploadPoster(id, fd)
    const rel = resp?.path || resp?.url || resp
    if (typeof rel === 'string') {
      posterUrl.value = `${BASE_URL}${rel}`
      ElMessage.success('海报上传成功')
    } else {
      ElMessage.success('海报上传成功')
      await load()
    }
  } catch (err) {
    ElMessage.error(err?.message || '上传失败')
  } finally {
    posterUploading.value = false
    // 清空选择
    e.target.value = ''
  }
}

// 票务批量编辑
const tickets = ref([])
const loadingTickets = ref(false)
const savingTickets = ref(false)
const deleteIds = ref([])

async function loadTickets() {
  try {
    loadingTickets.value = true
    const id = route.params.id
    const data = await eventAPI.getEventTickets(id)
    const list = Array.isArray(data?.content) ? data.content : (Array.isArray(data) ? data : [])
    tickets.value = list.map(t => ({
      id: t.id ?? null,
      ticketType: t.ticketType ?? '',
      price: t.price ?? 0,
      seatArea: t.seatArea ?? '',
      seatRow: t.seatRow ?? '',
      seatNumber: t.seatNumber ?? '',
      status: t.status ?? 1
    }))
  } catch (err) {
    ElMessage.error(err?.message || '加载票务失败')
  } finally {
    loadingTickets.value = false
  }
}

function addTicketRow() {
  tickets.value.push({ id: null, ticketType: '', price: 0, seatArea: '', seatRow: '', seatNumber: '', status: 1 })
}
function removeTicketRow(row, idx) {
  if (row.id) deleteIds.value.push(row.id)
  tickets.value.splice(idx, 1)
}
async function saveTicketsBatch() {
  try {
    // 基础校验
    for (const t of tickets.value) {
      if (!t.ticketType) throw new Error('存在未填写的票种')
      if (t.price == null || Number(t.price) < 0) throw new Error('价格必须为非负数')
    }
    savingTickets.value = true
    const id = route.params.id
    const payload = {
      tickets: tickets.value.map(t => ({ id: t.id ?? null, ticketType: t.ticketType, price: t.price, seatArea: t.seatArea, seatRow: t.seatRow, seatNumber: t.seatNumber, status: t.status })),
      deleteIds: deleteIds.value
    }
    await eventAPI.updateTicketsBatch(id, payload)
    ElMessage.success('票务批量变更已保存')
    deleteIds.value = []
    await loadTickets()
  } catch (err) {
    ElMessage.error(err?.message || '保存票务失败')
  } finally {
    savingTickets.value = false
  }
}

onMounted(load)
</script>

<style scoped>
 .event-detail-view { padding: 20px; min-height: 100vh; overflow-y: auto; }
.detail-card { padding: 12px; }
.detail-header { display: flex; gap: 16px; }
.poster { width: 180px; height: 240px; object-fit: cover; border-radius: 6px; }
.info h2 { margin: 0 0 8px 0; }
.poster-actions { margin-top: 8px; }
.desc { margin-top: 12px; }
.desc .pre { white-space: pre-wrap; line-height: 1.6; }
.actions { margin-top: 12px; display: flex; gap: 12px; }
.edit-form { margin-top: 12px; }
.w-160 { width: 160px; }
.w-140 { width: 140px; }
.tickets-edit { margin-top: 12px; }
.tickets-toolbar { display: flex; gap: 12px; margin-bottom: 8px; }
.hidden-input { display: none; }
.hint { color: #909399; margin-top: 8px; }
 .poster-upload { display: flex; align-items: center; gap: 12px; }
 .poster-sm { width: 120px; height: 160px; object-fit: cover; border-radius: 6px; }
</style>